package com.example.concurrentprogramming8016.thread.Atomic;

import java.util.Collection;
import java.util.SplittableRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author liyanhao
 * @Date 2023-01-03 19:21
 * 对象属性原子修改器
 * AtomicIntegerFieldUpdater可以线程安全地更新对象中的整型变量
 */
public class AtomicIntegerFieldUpdaterTest {
    public static class Candidate {
        volatile int score = 0;
        AtomicInteger score2 = new AtomicInteger();
    }

    public static final AtomicIntegerFieldUpdater<Candidate> scoreUpdate =
            AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");
    public static AtomicInteger realScore = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        final Candidate candidate = new Candidate();
        Thread[] threads = new Thread[10000];
        for (int i = 0; i < 10000; i++) {
            threads[i] = new Thread(() -> {
                if (Math.random() > 0.4) {
                    candidate.score2.incrementAndGet();
                    scoreUpdate.incrementAndGet(candidate);
                    realScore.incrementAndGet();
                }
            });
            threads[i].start();
        }
        for (int i = 0; i < 10000; i++) {
            threads[i].join();
        }
        System.out.println("AtomicIntegerFieldUpdaterScore=" + candidate.score);
        System.out.println("AtomicIntegerScore="+candidate.score2.get());
        System.out.println("realScore="+realScore.get());
    }
}
